import os
from os import path
from ruamel import yaml
import diceUtil
from config import *

# 预定路径
data_path = path.dirname(path.dirname(path.dirname(__file__))) + '/dataSource/'

def get_name(user_id):
    try:
        user_id = str(user_id)
        y_path = data_path + user_id + '.yaml'
        a = open(y_path, "r")
        dic = yaml.load(a.read(), Loader=yaml.Loader)
        return dic.get('current_name')
    except:
        return None

def get_attribute(user_id):
    try:
        user_id = str(user_id)
        y_path = data_path + user_id + '.yaml'
        a = open(y_path, "r")
        dic = yaml.load(a.read(), Loader=yaml.Loader)
        name = dic.get('current_name')
        return dic.get(name).get('attribute')
    except IOError:
        return None
    else:
        return None


def init_attribute():
    attribute = {}
    for name in ATTRIBUTE:
        attr = gen_one_attribute()
        attribute[name] = attr
    return attr


def gen_one_attribute():
    test = [diceUtil.range(6), diceUtil.range(6), diceUtil.range(6), diceUtil.range(6)]
    test.sort(reverse=True)
    print(test)
    return test[0] + test[1] + test[2]


def add_user(user_id, name):
    user_id = str(user_id)
    y_path = data_path + user_id + '.yaml'
    if not os.path.exists(y_path):  # 判断当前路径是否存在，没有则创建new文件夹
        file = open(y_path, 'w')
        file.close()
    a = open(y_path, "r")
    dic = yaml.load(a.read(), Loader=yaml.Loader)
    if dic is None:
        dic = {}
    dic['current_user'] = name
    dic[name]['name'] = name
    dic[name]['status'] = 'gen'
    attr = init_attribute()
    dic[name]['attribute'] = attr
    with open(y_path, "w", encoding="utf-8") as f:
        yaml.dump(dic, f, Dumper=yaml.RoundTripDumper)

# def swap(user_id,attr1,attr2):


#todo 更新人物信息
def updateUser(user_id,user_name,content):
    user_id = str(user_id)
    y_path = data_path + user_id + '.yaml'
    if not os.path.exists(y_path):  # 判断当前路径是否存在，没有则创建new文件夹
        file = open(y_path, 'w')
        file.close()
    a = open(y_path, "r")
    dic = yaml.load(a.read(), Loader=yaml.Loader)
    if dic is None:
        dic = {}
    dic['current_user'] = user_name
    dic[user_name]['name'] = user_name
    dic[user_name]['status'] = 'gen'
    attr = init_attribute()
    dic[user_name]['attribute'] = attr
    with open(y_path, "w", encoding="utf-8") as f:
        yaml.dump(dic, f, Dumper=yaml.RoundTripDumper)

